package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.strategy.OrderTradeStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * OrderTradeStrategyContext 策略上下文对象，管理所有的策略实现类
 *
 * @author Petrichor
 * @version 2024/01/05 20:51
 **/
@Service
public class OrderTradeStrategyContext implements ApplicationContextAware {
    /**
     * @description: 定义一个Map, Map就是付款项目的取值：1001 ， 1002 ， 1003
     * @author Petrichor
     * @date 2024/1/5 21:01
     **/
    public static final Map<String, OrderTradeStrategy> TRADE_INFO_STRATGY_MAP = new HashMap<>();

    /**
     * @description: 根据付款项目的取值获取对应的策略实现类对象
     * @author Petrichor
     * @date 2024/1/5 21:02
     **/
    public static OrderTradeStrategy getOrderTradeStrategy(String itemType) {
        OrderTradeStrategy orderTradeStrategy = TRADE_INFO_STRATGY_MAP.get(itemType);
        return orderTradeStrategy;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        // 使用spring容器
        Map<String, OrderTradeStrategy> beansOfType = applicationContext.getBeansOfType(OrderTradeStrategy.class);
        beansOfType.values().forEach(orderTradeStrategy -> {
            String itemType = orderTradeStrategy.getItemType();
            TRADE_INFO_STRATGY_MAP.put(itemType, orderTradeStrategy);
        });
    }
}


